<!DOCTYPE html>
<html>
<head>
    <title>django-websocket</title>
</head>
<body>
<div id="Q"></div>
<script src="/static/js/webs.js"></script>
<script>
{#    var _ws = WebS('/flow/');#}
{#    _ws.onmessage = function (evt) {#}
{#        var $this = JSON.parse(evt.data);#}
{#        console.log($this);#}
{#    };#}


    let ws = WebS('/flow/');
    ws.last_health_time = -1; // 上一次心跳时间
    ws.keepalive = function () {
        let time = new Date().getTime();
        if (ws.last_health_time !== -1 && time - ws.last_health_time > 20000) { // 不是刚开始连接并且20s
            ws.close()
        } else {
            // 如果断网了，ws.send会无法发送消息出去。ws.bufferedAmount不会为0。
            if (ws.bufferedAmount === 0 && ws.readyState === 1) {
                ws.send('1');
                ws.last_health_time = time;
            }
        }
{#        console.log(ws);#}
    };
    if (ws) {
        let reconnect = 0; //重连的时间
        let reconnectMark = false; //是否重连过
        ws.onopen = () => {
            console.log('ws连接成功！');
            reconnect = 0;
            reconnectMark = false;
{#            ws.receiveMessageTimer = setTimeout(() => {#}
{#                ws.close();#}
{#            }, 30000); // 30s没收到信息，代表服务器出问题了，关闭连接。如果收到消息了，重置该定时器。#}

            if (ws.readyState === 1) { // 为1表示连接处于open状态
                ws.keepAliveTimer = setInterval(() => {
                    ws.keepalive();
                }, 1000)
            }
        };
        ws.onerror = (evt) => {
            console.error('error: ' + evt)
        };
        ws.onmessage = (msg) => {
            // 收到消息，重置定时器
            clearTimeout(ws.receiveMessageTimer);
            var $this = JSON.parse(msg.data);
{#            console.log($this);#}
            console.log(msg);
            document.write('<p>' + msg.data + '</p>');
            ws.receiveMessageTimer = setTimeout(() => {
                ws.close();
            }, 30000); // 30s没收到信息，代表服务器出问题了，关闭连接。
        };
        ws.onclose = () => {
            console.log('Ws 断开！');
            clearTimeout(ws.receiveMessageTimer);
            clearInterval(ws.keepAliveTimer);
            if (!reconnectMark) { // 如果没有重连过，进行重连。
                reconnect = new Date().getTime();
                reconnectMark = true;
            }
            let tempWs = ws; // 保存ws对象
            if (new Date().getTime() - reconnect >= 20000) { // 20秒中重连，连不上就不连了
                ws.close();
                return false;
            } else {
                ws = WebS('/flow/');
                ws.onopen = tempWs.onopen;
                ws.onmessage = tempWs.onmessage;
                ws.onerror = tempWs.onerror;
                ws.onclose = tempWs.onclose;
                ws.keepalive = tempWs.keepalive;
                ws.last_health_time = -1;
            }
        }
    }


</script>
</body>
</html>
